import { createSlice } from '@reduxjs/toolkit'
import { getCategoryDataListApi } from '@/service/categoryApi'

const cateSlice = createSlice({
  name: 'cate',
  initialState: {
    category: null,
    material: null
  },
  reducers: {
    setCateDataList(state, { payload }) {
      state.category = payload.category
      state.material = payload.material
    }
  }
})

export const { setCateDataList } = cateSlice.actions

// 中间件
export const fetchCategoryDataListAction = () => async (dispatch, getState) => {
  // 如果有请求过，且state中有数据，就不再请求
  const state = getState()
  if (state.cate.category === null) {
    let ret = await getCategoryDataListApi()
    dispatch(setCateDataList(ret.data))
  }
}

export default cateSlice.reducer
